package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired(required = false)
    private DishService dishService;
    @Autowired(required = false)
    private HttpSession session;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        //1.获取登入数据id
        Long id = (Long) session.getAttribute("employee");

        //2.完善数据(创建人 修改人)
        dishDto.setCreateUser(id);
        dishDto.setUpdateUser(id);

        //3.调用业务层添加
        dishService.sava(dishDto);

        //4.返回
        return R.success("添加成功");
    }

    //菜品分页查询
    @RequestMapping("/page")
    public R<Page<DishDto>> findByPage(Integer page,Integer pageSize,String name){
        //1.调用业务层
        Page<DishDto> pageObj = dishService.findByPage(page, pageSize, name);

        return R.success(pageObj);
    }

    //根据id查询菜品和多个口味(回显数据)
    @GetMapping("/{id}")
    public R<DishDto> findById(@PathVariable Long id){
        //1.调用业务层
        DishDto dishDto = dishService.findById(id);

        //2.返回
        return R.success(dishDto);
    }


    @RequestMapping("/list")
    public R<List<DishDto>> findByCategoryId(Long categoryId,Integer status){
        //1.调用业务层查询id的菜品列表
        List<DishDto> dishList = dishService.findByCategoryId(categoryId,status);

        //2.返回数据
        return R.success(dishList);
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        //1.获取当前登入人
        Long id = (Long) session.getAttribute("employee");

        //设置修改人
        dishDto.setUpdateUser(id);

        //调用业务层
        dishService.update(dishDto);

        return R.success("修改菜品成功");
    }
}
